package com.qbw.app.module.vehicle.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.databinding.VehicleActivityTireBinding;
import com.qbw.app.manager.GeneralManager;
import com.qbw.app.model.TireData;
import com.qbw.app.model.Vehicle;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.module.vehicle.VehicleDataBindingAdapter;
import com.qbw.app.request.impl.VehicleRequest;
import com.qbw.customview.RefreshLoadMoreLayout;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 胎压状况
 * @author xiansx
 * @date 2020-08-13
 */
public class VehicleTireActivity extends CommonActivity<VehicleActivityTireBinding> {

    private Vehicle mVehicle;
    private TireData mTireData;

    public static void startActivity(Context context, Vehicle mVehicle) {
        Intent intent = new Intent(context, VehicleTireActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_VEHICLE, mVehicle);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.vehicle_activity_tire;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
        mVehicle = (Vehicle)args.getSerializable(Constant.KEY_VEHICLE);
        mBinding.title.setSubTitle(mVehicle.getVehicleNick());
        mBinding.title.setSubTitleVisible(true);
        mBinding.title.setListener(this);
        mBinding.executePendingBindings();
        mBinding.rll.init(new RefreshLoadMoreLayout.Config(this).canLoadMore(false));

    }

    /**
     * 更新UI
     */
    private void udateUI() {
        if(mTireData != null) {
//            VehicleDataBindingAdapter.setVehicleLastUpdateTime(mBinding.tvTireLastUpdatetime,
//                    data.getLastUpdateTime());
//            tv_tire_last_updatetime
            setUpdateTime();
            List<TireData.WheelState> frontWheel = mTireData.getFrontWheel();
            updateWheelUI(frontWheel, mBinding.tvPreTransport, mBinding.tvPreBattery, mBinding.tvPrePress, mBinding.tvPreTemp);
            List<TireData.WheelState> backWheel = mTireData.getBackWheel();
            updateWheelUI(backWheel, mBinding.tvNextTransport, mBinding.tvNextBattery, mBinding.tvNextPress, mBinding.tvNextTemp);
        }
    }

    private void setUpdateTime(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        mBinding.tvTireLastUpdatetime.setText(String.format(ResUtil.getString(R.string.last_update_time_format), df.format(new Date())));
    }

    private void updateWheelUI(List<TireData.WheelState> wheel,
                                    TextView tvTransport, TextView tvBattery,
                                    TextView tvPress, TextView tvTemp) {
        if(wheel != null && wheel.size() > 0) {
            for (int i = 0; i < wheel.size(); i++) {
                TireData.WheelState wheelState = wheel.get(i);
                if(wheelState != null) {
                    // 后轮数据类型，1：传感器传输状态；2：传感器电池电量；3： 后轮胎压；4：后轮温度
                    int faultid = wheelState.getFaultId();
                    // 1，正常；2过低、无信号；3过高
                    int states = wheelState.getStatus();
                    // 对应胎压 温度数值
                    int value = wheelState.getValue();
                    int msgResid = -1;
                    int iconResid = -1;
                    int colorResid = -1;
                    String msg = "";
                    if(faultid == 1) {
                        // 传感器传输状态：包含正常、无信号两种状态；
                        if(states == 1) {
                            msgResid = R.string.nm_tire_label_normal;
                        } else if(states == 2) {
                            msgResid = R.string.nm_tire_label_nosignal;
                        } else if(states == 3){
                        }
                        msg = getString(msgResid);

                        tvTransport.setText(msg);
                        if(colorResid > 0) {
                            tvTransport.setTextColor(this.getResources().getColor(colorResid));
                        }
                        if(iconResid > 0) {
                            tvTransport.setCompoundDrawablesWithIntrinsicBounds(null, null, this.getResources().getDrawable(iconResid), null);
                        }
                    } else if(faultid == 2) {
                        // 传感器电池电量：包含正常、低电两种状态。低电采用红色字体+向下箭头图标显示；
                        if(states == 1) {
                            msgResid = R.string.nm_tire_label_normal;
                        } else if(states == 2) {
                            msgResid = R.string.nm_tire_label_lowbattery;
                            iconResid = R.drawable.nm_icon_down_red;
                            colorResid = R.color.nm_tirestatus_red;
                        } else if(states == 3){
                        }
                        msg = getString(msgResid);

                        tvBattery.setText(msg);
                        if(colorResid > 0) {
                            tvBattery.setTextColor(this.getResources().getColor(colorResid));
                        }
                        if(iconResid > 0) {
                            tvBattery.setCompoundDrawablesWithIntrinsicBounds(null, null, this.getResources().getDrawable(iconResid), null);
                        }
                    } else if(faultid == 3) {
                        // 胎压：包含正常、过高、过低三种状态。过高和过低采用红色字体+向下箭头图标显示；
                        if(states == 1) {
                            msgResid = R.string.nm_tire_label_normalpress;
                        } else if(states == 2) {
                            msgResid = R.string.nm_tire_label_lowpress;
                            iconResid = R.drawable.nm_icon_down_red;
                            colorResid = R.color.nm_tirestatus_red;
                        } else if(states == 3){
                            msgResid = R.string.nm_tire_label_highpress;
                            iconResid = R.drawable.nm_icon_up_red;
                            colorResid = R.color.nm_tirestatus_red;
                        }
                        msg = String.format(getString(msgResid), value);

                        tvPress.setText(msg);
                        if(colorResid > 0) {
                            tvPress.setTextColor(this.getResources().getColor(colorResid));
                        }
                        if(iconResid > 0) {
                            tvPress.setCompoundDrawablesWithIntrinsicBounds(null, null, this.getResources().getDrawable(iconResid), null);
                        }
                    } else if(faultid == 4) {
                        // 轮胎温度：包含正常、过高两种状态。过高采用红色字体+向下箭头图标显示；
                        if(states == 1) {
                            msgResid = R.string.nm_tire_label_normaltemp;
                        } else if(states == 2) {
                        } else if(states == 3){
                            msgResid = R.string.nm_tire_label_hightemp;
                            iconResid = R.drawable.nm_icon_up_red;
                            colorResid = R.color.nm_tirestatus_red;
                        }
                        msg = String.format(getString(msgResid), value);

                        tvTemp.setText(msg);
                        if(colorResid > 0) {
                            tvTemp.setTextColor(this.getResources().getColor(colorResid));
                        }
                        if(iconResid > 0) {
                            tvTemp.setCompoundDrawablesWithIntrinsicBounds(null, null, this.getResources().getDrawable(iconResid), null);
                        }
                    }
                }
            }
        }
    }

    /**
     * 查看轮胎胎压状态
     */
    private void getTirePressureDataNm() {
        if(!TextUtils.isEmpty(mVehicle.getVehicleCode())) {
            mGeneralManager.getRequestManager()
                    .getVehicleRequest()
                    .getTirePressureDataNm(mVehicle.getVehicleCode(),
                            this)
                    .execute();
        }
    }

    @Override
    public void onRefresh() {
        getTirePressureDataNm();
    }

    @Override
    public void onHttpStart(HttpTask httpTask) {

    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        mBinding.rll.stopRefresh();
        String method = httpTask.getMethod();
        if (method.equals(VehicleRequest.METHOD_TIRE_DATA_V)) {
            TireData.Response response = (TireData.Response) entity;
            mTireData = response.getData();
            if(mTireData !=null){
                udateUI();
            }else{
                Toast.makeText(this,"数据为空",Toast.LENGTH_SHORT).show();
            }

        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        UniversalToastUtil.showToast(HttpRequestUtil.getMessage(errorCode, message));
        mBinding.rll.stopRefresh();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getTirePressureDataNm();
    }

}
